
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>4. Kaleidoscope: Adding JIT and Optimizer Support &mdash; LLVM 3.7 documentation</title>
    
    <link rel="stylesheet" href="../_static/llvm-theme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '3.7',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="top" title="LLVM 3.7 documentation" href="../index.html" />
    <link rel="up" title="LLVM Tutorial: Table of Contents" href="index.html" />
    <link rel="next" title="5. Kaleidoscope: Extending the Language: Control Flow" href="OCamlLangImpl5.html" />
    <link rel="prev" title="3. Kaleidoscope: Code generation to LLVM IR" href="OCamlLangImpl3.html" />
<style type="text/css">
  table.right { float: right; margin-left: 20px; }
  table.right td { border: 1px solid #ccc; }
</style>

  </head>
  <body role="document">
<div class="logo">
  <a href="../index.html">
    <img src="../_static/logo.png"
         alt="LLVM Logo" width="250" height="88"/></a>
</div>

    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="OCamlLangImpl5.html" title="5. Kaleidoscope: Extending the Language: Control Flow"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="OCamlLangImpl3.html" title="3. Kaleidoscope: Code generation to LLVM IR"
             accesskey="P">previous</a> |</li>
  <li><a href="http://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
  <li><a href="../index.html">Documentation</a>&raquo;</li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">LLVM Tutorial: Table of Contents</a> &raquo;</li> 
      </ul>
    </div>


    <div class="document">
      <div class="documentwrapper">
          <div class="body" role="main">
            
  <div class="section" id="kaleidoscope-adding-jit-and-optimizer-support">
<h1>4. Kaleidoscope: Adding JIT and Optimizer Support<a class="headerlink" href="#kaleidoscope-adding-jit-and-optimizer-support" title="Permalink to this headline">¶</a></h1>
<div class="contents local topic" id="contents">
<ul class="simple">
<li><a class="reference internal" href="#chapter-4-introduction" id="id1">Chapter 4 Introduction</a></li>
<li><a class="reference internal" href="#trivial-constant-folding" id="id2">Trivial Constant Folding</a></li>
<li><a class="reference internal" href="#llvm-optimization-passes" id="id3">LLVM Optimization Passes</a></li>
<li><a class="reference internal" href="#adding-a-jit-compiler" id="id4">Adding a JIT Compiler</a></li>
<li><a class="reference internal" href="#full-code-listing" id="id5">Full Code Listing</a></li>
</ul>
</div>
<div class="section" id="chapter-4-introduction">
<h2><a class="toc-backref" href="#id1">4.1. Chapter 4 Introduction</a><a class="headerlink" href="#chapter-4-introduction" title="Permalink to this headline">¶</a></h2>
<p>Welcome to Chapter 4 of the &#8220;<a class="reference external" href="index.html">Implementing a language with
LLVM</a>&#8221; tutorial. Chapters 1-3 described the implementation
of a simple language and added support for generating LLVM IR. This
chapter describes two new techniques: adding optimizer support to your
language, and adding JIT compiler support. These additions will
demonstrate how to get nice, efficient code for the Kaleidoscope
language.</p>
</div>
<div class="section" id="trivial-constant-folding">
<h2><a class="toc-backref" href="#id2">4.2. Trivial Constant Folding</a><a class="headerlink" href="#trivial-constant-folding" title="Permalink to this headline">¶</a></h2>
<p><strong>Note:</strong> the default <code class="docutils literal"><span class="pre">IRBuilder</span></code> now always includes the constant
folding optimisations below.</p>
<p>Our demonstration for Chapter 3 is elegant and easy to extend.
Unfortunately, it does not produce wonderful code. For example, when
compiling simple code, we don&#8217;t get obvious optimizations:</p>
<div class="highlight-python"><div class="highlight"><pre>ready&gt; def test(x) 1+2+x;
Read function definition:
define double @test(double %x) {
entry:
        %addtmp = fadd double 1.000000e+00, 2.000000e+00
        %addtmp1 = fadd double %addtmp, %x
        ret double %addtmp1
}
</pre></div>
</div>
<p>This code is a very, very literal transcription of the AST built by
parsing the input. As such, this transcription lacks optimizations like
constant folding (we&#8217;d like to get &#8220;<code class="docutils literal"><span class="pre">add</span> <span class="pre">x,</span> <span class="pre">3.0</span></code>&#8221; in the example
above) as well as other more important optimizations. Constant folding,
in particular, is a very common and very important optimization: so much
so that many language implementors implement constant folding support in
their AST representation.</p>
<p>With LLVM, you don&#8217;t need this support in the AST. Since all calls to
build LLVM IR go through the LLVM builder, it would be nice if the
builder itself checked to see if there was a constant folding
opportunity when you call it. If so, it could just do the constant fold
and return the constant instead of creating an instruction. This is
exactly what the <code class="docutils literal"><span class="pre">LLVMFoldingBuilder</span></code> class does.</p>
<p>All we did was switch from <code class="docutils literal"><span class="pre">LLVMBuilder</span></code> to <code class="docutils literal"><span class="pre">LLVMFoldingBuilder</span></code>.
Though we change no other code, we now have all of our instructions
implicitly constant folded without us having to do anything about it.
For example, the input above now compiles to:</p>
<div class="highlight-python"><div class="highlight"><pre>ready&gt; def test(x) 1+2+x;
Read function definition:
define double @test(double %x) {
entry:
        %addtmp = fadd double 3.000000e+00, %x
        ret double %addtmp
}
</pre></div>
</div>
<p>Well, that was easy :). In practice, we recommend always using
<code class="docutils literal"><span class="pre">LLVMFoldingBuilder</span></code> when generating code like this. It has no
&#8220;syntactic overhead&#8221; for its use (you don&#8217;t have to uglify your compiler
with constant checks everywhere) and it can dramatically reduce the
amount of LLVM IR that is generated in some cases (particular for
languages with a macro preprocessor or that use a lot of constants).</p>
<p>On the other hand, the <code class="docutils literal"><span class="pre">LLVMFoldingBuilder</span></code> is limited by the fact
that it does all of its analysis inline with the code as it is built. If
you take a slightly more complex example:</p>
<div class="highlight-python"><div class="highlight"><pre>ready&gt; def test(x) (1+2+x)*(x+(1+2));
ready&gt; Read function definition:
define double @test(double %x) {
entry:
        %addtmp = fadd double 3.000000e+00, %x
        %addtmp1 = fadd double %x, 3.000000e+00
        %multmp = fmul double %addtmp, %addtmp1
        ret double %multmp
}
</pre></div>
</div>
<p>In this case, the LHS and RHS of the multiplication are the same value.
We&#8217;d really like to see this generate &#8220;<code class="docutils literal"><span class="pre">tmp</span> <span class="pre">=</span> <span class="pre">x+3;</span> <span class="pre">result</span> <span class="pre">=</span> <span class="pre">tmp*tmp;</span></code>&#8221;
instead of computing &#8220;<code class="docutils literal"><span class="pre">x*3</span></code>&#8221; twice.</p>
<p>Unfortunately, no amount of local analysis will be able to detect and
correct this. This requires two transformations: reassociation of
expressions (to make the add&#8217;s lexically identical) and Common
Subexpression Elimination (CSE) to delete the redundant add instruction.
Fortunately, LLVM provides a broad range of optimizations that you can
use, in the form of &#8220;passes&#8221;.</p>
</div>
<div class="section" id="llvm-optimization-passes">
<h2><a class="toc-backref" href="#id3">4.3. LLVM Optimization Passes</a><a class="headerlink" href="#llvm-optimization-passes" title="Permalink to this headline">¶</a></h2>
<p>LLVM provides many optimization passes, which do many different sorts of
things and have different tradeoffs. Unlike other systems, LLVM doesn&#8217;t
hold to the mistaken notion that one set of optimizations is right for
all languages and for all situations. LLVM allows a compiler implementor
to make complete decisions about what optimizations to use, in which
order, and in what situation.</p>
<p>As a concrete example, LLVM supports both &#8220;whole module&#8221; passes, which
look across as large of body of code as they can (often a whole file,
but if run at link time, this can be a substantial portion of the whole
program). It also supports and includes &#8220;per-function&#8221; passes which just
operate on a single function at a time, without looking at other
functions. For more information on passes and how they are run, see the
<a class="reference external" href="../WritingAnLLVMPass.html">How to Write a Pass</a> document and the
<a class="reference external" href="../Passes.html">List of LLVM Passes</a>.</p>
<p>For Kaleidoscope, we are currently generating functions on the fly, one
at a time, as the user types them in. We aren&#8217;t shooting for the
ultimate optimization experience in this setting, but we also want to
catch the easy and quick stuff where possible. As such, we will choose
to run a few per-function optimizations as the user types the function
in. If we wanted to make a &#8220;static Kaleidoscope compiler&#8221;, we would use
exactly the code we have now, except that we would defer running the
optimizer until the entire file has been parsed.</p>
<p>In order to get per-function optimizations going, we need to set up a
<a class="reference external" href="../WritingAnLLVMPass.html#passmanager">Llvm.PassManager</a> to hold and
organize the LLVM optimizations that we want to run. Once we have that,
we can add a set of optimizations to run. The code looks like this:</p>
<div class="highlight-ocaml"><div class="highlight"><pre><span class="c">(* Create the JIT. *)</span>
<span class="k">let</span> <span class="n">the_execution_engine</span> <span class="o">=</span> <span class="nn">ExecutionEngine</span><span class="p">.</span><span class="n">create</span> <span class="nn">Codegen</span><span class="p">.</span><span class="n">the_module</span> <span class="k">in</span>
<span class="k">let</span> <span class="n">the_fpm</span> <span class="o">=</span> <span class="nn">PassManager</span><span class="p">.</span><span class="n">create_function</span> <span class="nn">Codegen</span><span class="p">.</span><span class="n">the_module</span> <span class="k">in</span>

<span class="c">(* Set up the optimizer pipeline.  Start with registering info about how the</span>
<span class="c"> * target lays out data structures. *)</span>
<span class="nn">DataLayout</span><span class="p">.</span><span class="n">add</span> <span class="o">(</span><span class="nn">ExecutionEngine</span><span class="p">.</span><span class="n">target_data</span> <span class="n">the_execution_engine</span><span class="o">)</span> <span class="n">the_fpm</span><span class="o">;</span>

<span class="c">(* Do simple &quot;peephole&quot; optimizations and bit-twiddling optzn. *)</span>
<span class="n">add_instruction_combining</span> <span class="n">the_fpm</span><span class="o">;</span>

<span class="c">(* reassociate expressions. *)</span>
<span class="n">add_reassociation</span> <span class="n">the_fpm</span><span class="o">;</span>

<span class="c">(* Eliminate Common SubExpressions. *)</span>
<span class="n">add_gvn</span> <span class="n">the_fpm</span><span class="o">;</span>

<span class="c">(* Simplify the control flow graph (deleting unreachable blocks, etc). *)</span>
<span class="n">add_cfg_simplification</span> <span class="n">the_fpm</span><span class="o">;</span>

<span class="n">ignore</span> <span class="o">(</span><span class="nn">PassManager</span><span class="p">.</span><span class="n">initialize</span> <span class="n">the_fpm</span><span class="o">);</span>

<span class="c">(* Run the main &quot;interpreter loop&quot; now. *)</span>
<span class="nn">Toplevel</span><span class="p">.</span><span class="n">main_loop</span> <span class="n">the_fpm</span> <span class="n">the_execution_engine</span> <span class="n">stream</span><span class="o">;</span>
</pre></div>
</div>
<p>The meat of the matter here, is the definition of &#8220;<code class="docutils literal"><span class="pre">the_fpm</span></code>&#8221;. It
requires a pointer to the <code class="docutils literal"><span class="pre">the_module</span></code> to construct itself. Once it is
set up, we use a series of &#8220;add&#8221; calls to add a bunch of LLVM passes.
The first pass is basically boilerplate, it adds a pass so that later
optimizations know how the data structures in the program are laid out.
The &#8220;<code class="docutils literal"><span class="pre">the_execution_engine</span></code>&#8221; variable is related to the JIT, which we
will get to in the next section.</p>
<p>In this case, we choose to add 4 optimization passes. The passes we
chose here are a pretty standard set of &#8220;cleanup&#8221; optimizations that are
useful for a wide variety of code. I won&#8217;t delve into what they do but,
believe me, they are a good starting place :).</p>
<p>Once the <code class="docutils literal"><span class="pre">Llvm.PassManager.</span></code> is set up, we need to make use of it. We
do this by running it after our newly created function is constructed
(in <code class="docutils literal"><span class="pre">Codegen.codegen_func</span></code>), but before it is returned to the client:</p>
<div class="highlight-ocaml"><div class="highlight"><pre><span class="k">let</span> <span class="n">codegen_func</span> <span class="n">the_fpm</span> <span class="o">=</span> <span class="k">function</span>
      <span class="o">...</span>
      <span class="k">try</span>
        <span class="k">let</span> <span class="n">ret_val</span> <span class="o">=</span> <span class="n">codegen_expr</span> <span class="n">body</span> <span class="k">in</span>

        <span class="c">(* Finish off the function. *)</span>
        <span class="k">let</span> <span class="o">_</span> <span class="o">=</span> <span class="n">build_ret</span> <span class="n">ret_val</span> <span class="n">builder</span> <span class="k">in</span>

        <span class="c">(* Validate the generated code, checking for consistency. *)</span>
        <span class="nn">Llvm_analysis</span><span class="p">.</span><span class="n">assert_valid_function</span> <span class="n">the_function</span><span class="o">;</span>

        <span class="c">(* Optimize the function. *)</span>
        <span class="k">let</span> <span class="o">_</span> <span class="o">=</span> <span class="nn">PassManager</span><span class="p">.</span><span class="n">run_function</span> <span class="n">the_function</span> <span class="n">the_fpm</span> <span class="k">in</span>

        <span class="n">the_function</span>
</pre></div>
</div>
<p>As you can see, this is pretty straightforward. The <code class="docutils literal"><span class="pre">the_fpm</span></code>
optimizes and updates the LLVM Function* in place, improving
(hopefully) its body. With this in place, we can try our test above
again:</p>
<div class="highlight-python"><div class="highlight"><pre>ready&gt; def test(x) (1+2+x)*(x+(1+2));
ready&gt; Read function definition:
define double @test(double %x) {
entry:
        %addtmp = fadd double %x, 3.000000e+00
        %multmp = fmul double %addtmp, %addtmp
        ret double %multmp
}
</pre></div>
</div>
<p>As expected, we now get our nicely optimized code, saving a floating
point add instruction from every execution of this function.</p>
<p>LLVM provides a wide variety of optimizations that can be used in
certain circumstances. Some <a class="reference external" href="../Passes.html">documentation about the various
passes</a> is available, but it isn&#8217;t very complete.
Another good source of ideas can come from looking at the passes that
<code class="docutils literal"><span class="pre">Clang</span></code> runs to get started. The &#8220;<code class="docutils literal"><span class="pre">opt</span></code>&#8221; tool allows you to
experiment with passes from the command line, so you can see if they do
anything.</p>
<p>Now that we have reasonable code coming out of our front-end, lets talk
about executing it!</p>
</div>
<div class="section" id="adding-a-jit-compiler">
<h2><a class="toc-backref" href="#id4">4.4. Adding a JIT Compiler</a><a class="headerlink" href="#adding-a-jit-compiler" title="Permalink to this headline">¶</a></h2>
<p>Code that is available in LLVM IR can have a wide variety of tools
applied to it. For example, you can run optimizations on it (as we did
above), you can dump it out in textual or binary forms, you can compile
the code to an assembly file (.s) for some target, or you can JIT
compile it. The nice thing about the LLVM IR representation is that it
is the &#8220;common currency&#8221; between many different parts of the compiler.</p>
<p>In this section, we&#8217;ll add JIT compiler support to our interpreter. The
basic idea that we want for Kaleidoscope is to have the user enter
function bodies as they do now, but immediately evaluate the top-level
expressions they type in. For example, if they type in &#8220;1 + 2;&#8221;, we
should evaluate and print out 3. If they define a function, they should
be able to call it from the command line.</p>
<p>In order to do this, we first declare and initialize the JIT. This is
done by adding a global variable and a call in <code class="docutils literal"><span class="pre">main</span></code>:</p>
<div class="highlight-ocaml"><div class="highlight"><pre><span class="o">...</span>
<span class="k">let</span> <span class="n">main</span> <span class="bp">()</span> <span class="o">=</span>
  <span class="o">...</span>
  <span class="c">(* Create the JIT. *)</span>
  <span class="k">let</span> <span class="n">the_execution_engine</span> <span class="o">=</span> <span class="nn">ExecutionEngine</span><span class="p">.</span><span class="n">create</span> <span class="nn">Codegen</span><span class="p">.</span><span class="n">the_module</span> <span class="k">in</span>
  <span class="o">...</span>
</pre></div>
</div>
<p>This creates an abstract &#8220;Execution Engine&#8221; which can be either a JIT
compiler or the LLVM interpreter. LLVM will automatically pick a JIT
compiler for you if one is available for your platform, otherwise it
will fall back to the interpreter.</p>
<p>Once the <code class="docutils literal"><span class="pre">Llvm_executionengine.ExecutionEngine.t</span></code> is created, the JIT
is ready to be used. There are a variety of APIs that are useful, but
the simplest one is the
&#8220;<code class="docutils literal"><span class="pre">Llvm_executionengine.ExecutionEngine.run_function</span></code>&#8221; function. This
method JIT compiles the specified LLVM Function and returns a function
pointer to the generated machine code. In our case, this means that we
can change the code that parses a top-level expression to look like
this:</p>
<div class="highlight-ocaml"><div class="highlight"><pre><span class="c">(* Evaluate a top-level expression into an anonymous function. *)</span>
<span class="k">let</span> <span class="n">e</span> <span class="o">=</span> <span class="nn">Parser</span><span class="p">.</span><span class="n">parse_toplevel</span> <span class="n">stream</span> <span class="k">in</span>
<span class="n">print_endline</span> <span class="s2">&quot;parsed a top-level expr&quot;</span><span class="o">;</span>
<span class="k">let</span> <span class="n">the_function</span> <span class="o">=</span> <span class="nn">Codegen</span><span class="p">.</span><span class="n">codegen_func</span> <span class="n">the_fpm</span> <span class="n">e</span> <span class="k">in</span>
<span class="n">dump_value</span> <span class="n">the_function</span><span class="o">;</span>

<span class="c">(* JIT the function, returning a function pointer. *)</span>
<span class="k">let</span> <span class="n">result</span> <span class="o">=</span> <span class="nn">ExecutionEngine</span><span class="p">.</span><span class="n">run_function</span> <span class="n">the_function</span> <span class="o">[||]</span>
  <span class="n">the_execution_engine</span> <span class="k">in</span>

<span class="n">print_string</span> <span class="s2">&quot;Evaluated to &quot;</span><span class="o">;</span>
<span class="n">print_float</span> <span class="o">(</span><span class="nn">GenericValue</span><span class="p">.</span><span class="n">as_float</span> <span class="nn">Codegen</span><span class="p">.</span><span class="n">double_type</span> <span class="n">result</span><span class="o">);</span>
<span class="n">print_newline</span> <span class="bp">()</span><span class="o">;</span>
</pre></div>
</div>
<p>Recall that we compile top-level expressions into a self-contained LLVM
function that takes no arguments and returns the computed double.
Because the LLVM JIT compiler matches the native platform ABI, this
means that you can just cast the result pointer to a function pointer of
that type and call it directly. This means, there is no difference
between JIT compiled code and native machine code that is statically
linked into your application.</p>
<p>With just these two changes, lets see how Kaleidoscope works now!</p>
<div class="highlight-python"><div class="highlight"><pre>ready&gt; 4+5;
define double @&quot;&quot;() {
entry:
        ret double 9.000000e+00
}

Evaluated to 9.000000
</pre></div>
</div>
<p>Well this looks like it is basically working. The dump of the function
shows the &#8220;no argument function that always returns double&#8221; that we
synthesize for each top level expression that is typed in. This
demonstrates very basic functionality, but can we do more?</p>
<div class="highlight-python"><div class="highlight"><pre>ready&gt; def testfunc(x y) x + y*2;
Read function definition:
define double @testfunc(double %x, double %y) {
entry:
        %multmp = fmul double %y, 2.000000e+00
        %addtmp = fadd double %multmp, %x
        ret double %addtmp
}

ready&gt; testfunc(4, 10);
define double @&quot;&quot;() {
entry:
        %calltmp = call double @testfunc(double 4.000000e+00, double 1.000000e+01)
        ret double %calltmp
}

Evaluated to 24.000000
</pre></div>
</div>
<p>This illustrates that we can now call user code, but there is something
a bit subtle going on here. Note that we only invoke the JIT on the
anonymous functions that <em>call testfunc</em>, but we never invoked it on
<em>testfunc</em> itself. What actually happened here is that the JIT scanned
for all non-JIT&#8217;d functions transitively called from the anonymous
function and compiled all of them before returning from
<code class="docutils literal"><span class="pre">run_function</span></code>.</p>
<p>The JIT provides a number of other more advanced interfaces for things
like freeing allocated machine code, rejit&#8217;ing functions to update them,
etc. However, even with this simple code, we get some surprisingly
powerful capabilities - check this out (I removed the dump of the
anonymous functions, you should get the idea by now :) :</p>
<div class="highlight-python"><div class="highlight"><pre>ready&gt; extern sin(x);
Read extern:
declare double @sin(double)

ready&gt; extern cos(x);
Read extern:
declare double @cos(double)

ready&gt; sin(1.0);
Evaluated to 0.841471

ready&gt; def foo(x) sin(x)*sin(x) + cos(x)*cos(x);
Read function definition:
define double @foo(double %x) {
entry:
        %calltmp = call double @sin(double %x)
        %multmp = fmul double %calltmp, %calltmp
        %calltmp2 = call double @cos(double %x)
        %multmp4 = fmul double %calltmp2, %calltmp2
        %addtmp = fadd double %multmp, %multmp4
        ret double %addtmp
}

ready&gt; foo(4.0);
Evaluated to 1.000000
</pre></div>
</div>
<p>Whoa, how does the JIT know about sin and cos? The answer is
surprisingly simple: in this example, the JIT started execution of a
function and got to a function call. It realized that the function was
not yet JIT compiled and invoked the standard set of routines to resolve
the function. In this case, there is no body defined for the function,
so the JIT ended up calling &#8220;<code class="docutils literal"><span class="pre">dlsym(&quot;sin&quot;)</span></code>&#8221; on the Kaleidoscope
process itself. Since &#8220;<code class="docutils literal"><span class="pre">sin</span></code>&#8221; is defined within the JIT&#8217;s address
space, it simply patches up calls in the module to call the libm version
of <code class="docutils literal"><span class="pre">sin</span></code> directly.</p>
<p>The LLVM JIT provides a number of interfaces (look in the
<code class="docutils literal"><span class="pre">llvm_executionengine.mli</span></code> file) for controlling how unknown functions
get resolved. It allows you to establish explicit mappings between IR
objects and addresses (useful for LLVM global variables that you want to
map to static tables, for example), allows you to dynamically decide on
the fly based on the function name, and even allows you to have the JIT
compile functions lazily the first time they&#8217;re called.</p>
<p>One interesting application of this is that we can now extend the
language by writing arbitrary C code to implement operations. For
example, if we add:</p>
<div class="highlight-c++"><div class="highlight"><pre><span class="cm">/* putchard - putchar that takes a double and returns 0. */</span>
<span class="k">extern</span> <span class="s">&quot;C&quot;</span>
<span class="kt">double</span> <span class="n">putchard</span><span class="p">(</span><span class="kt">double</span> <span class="n">X</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">putchar</span><span class="p">((</span><span class="kt">char</span><span class="p">)</span><span class="n">X</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Now we can produce simple output to the console by using things like:
&#8220;<code class="docutils literal"><span class="pre">extern</span> <span class="pre">putchard(x);</span> <span class="pre">putchard(120);</span></code>&#8221;, which prints a lowercase &#8216;x&#8217;
on the console (120 is the ASCII code for &#8216;x&#8217;). Similar code could be
used to implement file I/O, console input, and many other capabilities
in Kaleidoscope.</p>
<p>This completes the JIT and optimizer chapter of the Kaleidoscope
tutorial. At this point, we can compile a non-Turing-complete
programming language, optimize and JIT compile it in a user-driven way.
Next up we&#8217;ll look into <a class="reference external" href="OCamlLangImpl5.html">extending the language with control flow
constructs</a>, tackling some interesting LLVM IR
issues along the way.</p>
</div>
<div class="section" id="full-code-listing">
<h2><a class="toc-backref" href="#id5">4.5. Full Code Listing</a><a class="headerlink" href="#full-code-listing" title="Permalink to this headline">¶</a></h2>
<p>Here is the complete code listing for our running example, enhanced with
the LLVM JIT and optimizer. To build this example, use:</p>
<div class="highlight-bash"><div class="highlight"><pre><span class="c"># Compile</span>
ocamlbuild toy.byte
<span class="c"># Run</span>
./toy.byte
</pre></div>
</div>
<p>Here is the code:</p>
<dl class="docutils">
<dt>_tags:</dt>
<dd><div class="first last highlight-python"><div class="highlight"><pre>&lt;{lexer,parser}.ml&gt;: use_camlp4, pp(camlp4of)
&lt;*.{byte,native}&gt;: g++, use_llvm, use_llvm_analysis
&lt;*.{byte,native}&gt;: use_llvm_executionengine, use_llvm_target
&lt;*.{byte,native}&gt;: use_llvm_scalar_opts, use_bindings
</pre></div>
</div>
</dd>
<dt>myocamlbuild.ml:</dt>
<dd><div class="first last highlight-ocaml"><div class="highlight"><pre><span class="k">open</span> <span class="nc">Ocamlbuild_plugin</span><span class="o">;;</span>

<span class="n">ocaml_lib</span> <span class="o">~</span><span class="n">extern</span><span class="o">:</span><span class="bp">true</span> <span class="s2">&quot;llvm&quot;</span><span class="o">;;</span>
<span class="n">ocaml_lib</span> <span class="o">~</span><span class="n">extern</span><span class="o">:</span><span class="bp">true</span> <span class="s2">&quot;llvm_analysis&quot;</span><span class="o">;;</span>
<span class="n">ocaml_lib</span> <span class="o">~</span><span class="n">extern</span><span class="o">:</span><span class="bp">true</span> <span class="s2">&quot;llvm_executionengine&quot;</span><span class="o">;;</span>
<span class="n">ocaml_lib</span> <span class="o">~</span><span class="n">extern</span><span class="o">:</span><span class="bp">true</span> <span class="s2">&quot;llvm_target&quot;</span><span class="o">;;</span>
<span class="n">ocaml_lib</span> <span class="o">~</span><span class="n">extern</span><span class="o">:</span><span class="bp">true</span> <span class="s2">&quot;llvm_scalar_opts&quot;</span><span class="o">;;</span>

<span class="n">flag</span> <span class="o">[</span><span class="s2">&quot;link&quot;</span><span class="o">;</span> <span class="s2">&quot;ocaml&quot;</span><span class="o">;</span> <span class="s2">&quot;g++&quot;</span><span class="o">]</span> <span class="o">(</span><span class="nc">S</span><span class="o">[</span><span class="nc">A</span><span class="s2">&quot;-cc&quot;</span><span class="o">;</span> <span class="nc">A</span><span class="s2">&quot;g++&quot;</span><span class="o">]);;</span>
<span class="n">dep</span> <span class="o">[</span><span class="s2">&quot;link&quot;</span><span class="o">;</span> <span class="s2">&quot;ocaml&quot;</span><span class="o">;</span> <span class="s2">&quot;use_bindings&quot;</span><span class="o">]</span> <span class="o">[</span><span class="s2">&quot;bindings.o&quot;</span><span class="o">];;</span>
</pre></div>
</div>
</dd>
<dt>token.ml:</dt>
<dd><div class="first last highlight-ocaml"><div class="highlight"><pre><span class="c">(*===----------------------------------------------------------------------===</span>
<span class="c"> * Lexer Tokens</span>
<span class="c"> *===----------------------------------------------------------------------===*)</span>

<span class="c">(* The lexer returns these &#39;Kwd&#39; if it is an unknown character, otherwise one of</span>
<span class="c"> * these others for known things. *)</span>
<span class="k">type</span> <span class="n">token</span> <span class="o">=</span>
  <span class="c">(* commands *)</span>
  <span class="o">|</span> <span class="nc">Def</span> <span class="o">|</span> <span class="nc">Extern</span>

  <span class="c">(* primary *)</span>
  <span class="o">|</span> <span class="nc">Ident</span> <span class="k">of</span> <span class="kt">string</span> <span class="o">|</span> <span class="nc">Number</span> <span class="k">of</span> <span class="kt">float</span>

  <span class="c">(* unknown *)</span>
  <span class="o">|</span> <span class="nc">Kwd</span> <span class="k">of</span> <span class="kt">char</span>
</pre></div>
</div>
</dd>
<dt>lexer.ml:</dt>
<dd><div class="first last highlight-ocaml"><div class="highlight"><pre><span class="c">(*===----------------------------------------------------------------------===</span>
<span class="c"> * Lexer</span>
<span class="c"> *===----------------------------------------------------------------------===*)</span>

<span class="k">let</span> <span class="k">rec</span> <span class="n">lex</span> <span class="o">=</span> <span class="n">parser</span>
  <span class="c">(* Skip any whitespace. *)</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span> <span class="o">(</span><span class="sc">&#39; &#39;</span> <span class="o">|</span> <span class="sc">&#39;\n&#39;</span> <span class="o">|</span> <span class="sc">&#39;\r&#39;</span> <span class="o">|</span> <span class="sc">&#39;\t&#39;</span><span class="o">);</span> <span class="n">stream</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="n">lex</span> <span class="n">stream</span>

  <span class="c">(* identifier: [a-zA-Z][a-zA-Z0-9] *)</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span> <span class="o">(</span><span class="sc">&#39;A&#39;</span> <span class="o">..</span> <span class="sc">&#39;Z&#39;</span> <span class="o">|</span> <span class="sc">&#39;a&#39;</span> <span class="o">..</span> <span class="sc">&#39;z&#39;</span> <span class="k">as</span> <span class="n">c</span><span class="o">);</span> <span class="n">stream</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span>
      <span class="k">let</span> <span class="n">buffer</span> <span class="o">=</span> <span class="nn">Buffer</span><span class="p">.</span><span class="n">create</span> <span class="mi">1</span> <span class="k">in</span>
      <span class="nn">Buffer</span><span class="p">.</span><span class="n">add_char</span> <span class="n">buffer</span> <span class="n">c</span><span class="o">;</span>
      <span class="n">lex_ident</span> <span class="n">buffer</span> <span class="n">stream</span>

  <span class="c">(* number: [0-9.]+ *)</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span> <span class="o">(</span><span class="sc">&#39;0&#39;</span> <span class="o">..</span> <span class="sc">&#39;9&#39;</span> <span class="k">as</span> <span class="n">c</span><span class="o">);</span> <span class="n">stream</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span>
      <span class="k">let</span> <span class="n">buffer</span> <span class="o">=</span> <span class="nn">Buffer</span><span class="p">.</span><span class="n">create</span> <span class="mi">1</span> <span class="k">in</span>
      <span class="nn">Buffer</span><span class="p">.</span><span class="n">add_char</span> <span class="n">buffer</span> <span class="n">c</span><span class="o">;</span>
      <span class="n">lex_number</span> <span class="n">buffer</span> <span class="n">stream</span>

  <span class="c">(* Comment until end of line. *)</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span> <span class="o">(</span><span class="sc">&#39;#&#39;</span><span class="o">);</span> <span class="n">stream</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span>
      <span class="n">lex_comment</span> <span class="n">stream</span>

  <span class="c">(* Otherwise, just return the character as its ascii value. *)</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="n">c</span><span class="o">;</span> <span class="n">stream</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span>
      <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Kwd</span> <span class="n">c</span><span class="o">;</span> <span class="n">lex</span> <span class="n">stream</span> <span class="o">&gt;]</span>

  <span class="c">(* end of stream. *)</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="o">[&lt;</span> <span class="o">&gt;]</span>

<span class="ow">and</span> <span class="n">lex_number</span> <span class="n">buffer</span> <span class="o">=</span> <span class="n">parser</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span> <span class="o">(</span><span class="sc">&#39;0&#39;</span> <span class="o">..</span> <span class="sc">&#39;9&#39;</span> <span class="o">|</span> <span class="sc">&#39;.&#39;</span> <span class="k">as</span> <span class="n">c</span><span class="o">);</span> <span class="n">stream</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span>
      <span class="nn">Buffer</span><span class="p">.</span><span class="n">add_char</span> <span class="n">buffer</span> <span class="n">c</span><span class="o">;</span>
      <span class="n">lex_number</span> <span class="n">buffer</span> <span class="n">stream</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="n">stream</span><span class="o">=</span><span class="n">lex</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span>
      <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Number</span> <span class="o">(</span><span class="n">float_of_string</span> <span class="o">(</span><span class="nn">Buffer</span><span class="p">.</span><span class="n">contents</span> <span class="n">buffer</span><span class="o">));</span> <span class="n">stream</span> <span class="o">&gt;]</span>

<span class="ow">and</span> <span class="n">lex_ident</span> <span class="n">buffer</span> <span class="o">=</span> <span class="n">parser</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span> <span class="o">(</span><span class="sc">&#39;A&#39;</span> <span class="o">..</span> <span class="sc">&#39;Z&#39;</span> <span class="o">|</span> <span class="sc">&#39;a&#39;</span> <span class="o">..</span> <span class="sc">&#39;z&#39;</span> <span class="o">|</span> <span class="sc">&#39;0&#39;</span> <span class="o">..</span> <span class="sc">&#39;9&#39;</span> <span class="k">as</span> <span class="n">c</span><span class="o">);</span> <span class="n">stream</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span>
      <span class="nn">Buffer</span><span class="p">.</span><span class="n">add_char</span> <span class="n">buffer</span> <span class="n">c</span><span class="o">;</span>
      <span class="n">lex_ident</span> <span class="n">buffer</span> <span class="n">stream</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="n">stream</span><span class="o">=</span><span class="n">lex</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span>
      <span class="k">match</span> <span class="nn">Buffer</span><span class="p">.</span><span class="n">contents</span> <span class="n">buffer</span> <span class="k">with</span>
      <span class="o">|</span> <span class="s2">&quot;def&quot;</span> <span class="o">-&gt;</span> <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Def</span><span class="o">;</span> <span class="n">stream</span> <span class="o">&gt;]</span>
      <span class="o">|</span> <span class="s2">&quot;extern&quot;</span> <span class="o">-&gt;</span> <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Extern</span><span class="o">;</span> <span class="n">stream</span> <span class="o">&gt;]</span>
      <span class="o">|</span> <span class="n">id</span> <span class="o">-&gt;</span> <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Ident</span> <span class="n">id</span><span class="o">;</span> <span class="n">stream</span> <span class="o">&gt;]</span>

<span class="ow">and</span> <span class="n">lex_comment</span> <span class="o">=</span> <span class="n">parser</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span> <span class="o">(</span><span class="sc">&#39;\n&#39;</span><span class="o">);</span> <span class="n">stream</span><span class="o">=</span><span class="n">lex</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="n">stream</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="n">c</span><span class="o">;</span> <span class="n">e</span><span class="o">=</span><span class="n">lex_comment</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="n">e</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="o">[&lt;</span> <span class="o">&gt;]</span>
</pre></div>
</div>
</dd>
<dt>ast.ml:</dt>
<dd><div class="first last highlight-ocaml"><div class="highlight"><pre><span class="c">(*===----------------------------------------------------------------------===</span>
<span class="c"> * Abstract Syntax Tree (aka Parse Tree)</span>
<span class="c"> *===----------------------------------------------------------------------===*)</span>

<span class="c">(* expr - Base type for all expression nodes. *)</span>
<span class="k">type</span> <span class="n">expr</span> <span class="o">=</span>
  <span class="c">(* variant for numeric literals like &quot;1.0&quot;. *)</span>
  <span class="o">|</span> <span class="nc">Number</span> <span class="k">of</span> <span class="kt">float</span>

  <span class="c">(* variant for referencing a variable, like &quot;a&quot;. *)</span>
  <span class="o">|</span> <span class="nc">Variable</span> <span class="k">of</span> <span class="kt">string</span>

  <span class="c">(* variant for a binary operator. *)</span>
  <span class="o">|</span> <span class="nc">Binary</span> <span class="k">of</span> <span class="kt">char</span> <span class="o">*</span> <span class="n">expr</span> <span class="o">*</span> <span class="n">expr</span>

  <span class="c">(* variant for function calls. *)</span>
  <span class="o">|</span> <span class="nc">Call</span> <span class="k">of</span> <span class="kt">string</span> <span class="o">*</span> <span class="n">expr</span> <span class="kt">array</span>

<span class="c">(* proto - This type represents the &quot;prototype&quot; for a function, which captures</span>
<span class="c"> * its name, and its argument names (thus implicitly the number of arguments the</span>
<span class="c"> * function takes). *)</span>
<span class="k">type</span> <span class="n">proto</span> <span class="o">=</span> <span class="nc">Prototype</span> <span class="k">of</span> <span class="kt">string</span> <span class="o">*</span> <span class="kt">string</span> <span class="kt">array</span>

<span class="c">(* func - This type represents a function definition itself. *)</span>
<span class="k">type</span> <span class="n">func</span> <span class="o">=</span> <span class="nc">Function</span> <span class="k">of</span> <span class="n">proto</span> <span class="o">*</span> <span class="n">expr</span>
</pre></div>
</div>
</dd>
<dt>parser.ml:</dt>
<dd><div class="first last highlight-ocaml"><div class="highlight"><pre><span class="c">(*===---------------------------------------------------------------------===</span>
<span class="c"> * Parser</span>
<span class="c"> *===---------------------------------------------------------------------===*)</span>

<span class="c">(* binop_precedence - This holds the precedence for each binary operator that is</span>
<span class="c"> * defined *)</span>
<span class="k">let</span> <span class="n">binop_precedence</span><span class="o">:(</span><span class="kt">char</span><span class="o">,</span> <span class="kt">int</span><span class="o">)</span> <span class="nn">Hashtbl</span><span class="p">.</span><span class="n">t</span> <span class="o">=</span> <span class="nn">Hashtbl</span><span class="p">.</span><span class="n">create</span> <span class="mi">10</span>

<span class="c">(* precedence - Get the precedence of the pending binary operator token. *)</span>
<span class="k">let</span> <span class="n">precedence</span> <span class="n">c</span> <span class="o">=</span> <span class="k">try</span> <span class="nn">Hashtbl</span><span class="p">.</span><span class="n">find</span> <span class="n">binop_precedence</span> <span class="n">c</span> <span class="k">with</span> <span class="nc">Not_found</span> <span class="o">-&gt;</span> <span class="o">-</span><span class="mi">1</span>

<span class="c">(* primary</span>
<span class="c"> *   ::= identifier</span>
<span class="c"> *   ::= numberexpr</span>
<span class="c"> *   ::= parenexpr *)</span>
<span class="k">let</span> <span class="k">rec</span> <span class="n">parse_primary</span> <span class="o">=</span> <span class="n">parser</span>
  <span class="c">(* numberexpr ::= number *)</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Number</span> <span class="n">n</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="nn">Ast</span><span class="p">.</span><span class="nc">Number</span> <span class="n">n</span>

  <span class="c">(* parenexpr ::= &#39;(&#39; expression &#39;)&#39; *)</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Kwd</span> <span class="sc">&#39;(&#39;</span><span class="o">;</span> <span class="n">e</span><span class="o">=</span><span class="n">parse_expr</span><span class="o">;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Kwd</span> <span class="sc">&#39;)&#39;</span> <span class="o">??</span> <span class="s2">&quot;expected &#39;)&#39;&quot;</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="n">e</span>

  <span class="c">(* identifierexpr</span>
<span class="c">   *   ::= identifier</span>
<span class="c">   *   ::= identifier &#39;(&#39; argumentexpr &#39;)&#39; *)</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Ident</span> <span class="n">id</span><span class="o">;</span> <span class="n">stream</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span>
      <span class="k">let</span> <span class="k">rec</span> <span class="n">parse_args</span> <span class="n">accumulator</span> <span class="o">=</span> <span class="n">parser</span>
        <span class="o">|</span> <span class="o">[&lt;</span> <span class="n">e</span><span class="o">=</span><span class="n">parse_expr</span><span class="o">;</span> <span class="n">stream</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span>
            <span class="k">begin</span> <span class="n">parser</span>
              <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Kwd</span> <span class="sc">&#39;,&#39;</span><span class="o">;</span> <span class="n">e</span><span class="o">=</span><span class="n">parse_args</span> <span class="o">(</span><span class="n">e</span> <span class="o">::</span> <span class="n">accumulator</span><span class="o">)</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="n">e</span>
              <span class="o">|</span> <span class="o">[&lt;</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="n">e</span> <span class="o">::</span> <span class="n">accumulator</span>
            <span class="k">end</span> <span class="n">stream</span>
        <span class="o">|</span> <span class="o">[&lt;</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="n">accumulator</span>
      <span class="k">in</span>
      <span class="k">let</span> <span class="k">rec</span> <span class="n">parse_ident</span> <span class="n">id</span> <span class="o">=</span> <span class="n">parser</span>
        <span class="c">(* Call. *)</span>
        <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Kwd</span> <span class="sc">&#39;(&#39;</span><span class="o">;</span>
             <span class="n">args</span><span class="o">=</span><span class="n">parse_args</span> <span class="bp">[]</span><span class="o">;</span>
             <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Kwd</span> <span class="sc">&#39;)&#39;</span> <span class="o">??</span> <span class="s2">&quot;expected &#39;)&#39;&quot;</span><span class="o">&gt;]</span> <span class="o">-&gt;</span>
            <span class="nn">Ast</span><span class="p">.</span><span class="nc">Call</span> <span class="o">(</span><span class="n">id</span><span class="o">,</span> <span class="nn">Array</span><span class="p">.</span><span class="n">of_list</span> <span class="o">(</span><span class="nn">List</span><span class="p">.</span><span class="n">rev</span> <span class="n">args</span><span class="o">))</span>

        <span class="c">(* Simple variable ref. *)</span>
        <span class="o">|</span> <span class="o">[&lt;</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="nn">Ast</span><span class="p">.</span><span class="nc">Variable</span> <span class="n">id</span>
      <span class="k">in</span>
      <span class="n">parse_ident</span> <span class="n">id</span> <span class="n">stream</span>

  <span class="o">|</span> <span class="o">[&lt;</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="k">raise</span> <span class="o">(</span><span class="nn">Stream</span><span class="p">.</span><span class="nc">Error</span> <span class="s2">&quot;unknown token when expecting an expression.&quot;</span><span class="o">)</span>

<span class="c">(* binoprhs</span>
<span class="c"> *   ::= (&#39;+&#39; primary)* *)</span>
<span class="ow">and</span> <span class="n">parse_bin_rhs</span> <span class="n">expr_prec</span> <span class="n">lhs</span> <span class="n">stream</span> <span class="o">=</span>
  <span class="k">match</span> <span class="nn">Stream</span><span class="p">.</span><span class="n">peek</span> <span class="n">stream</span> <span class="k">with</span>
  <span class="c">(* If this is a binop, find its precedence. *)</span>
  <span class="o">|</span> <span class="nc">Some</span> <span class="o">(</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Kwd</span> <span class="n">c</span><span class="o">)</span> <span class="k">when</span> <span class="nn">Hashtbl</span><span class="p">.</span><span class="n">mem</span> <span class="n">binop_precedence</span> <span class="n">c</span> <span class="o">-&gt;</span>
      <span class="k">let</span> <span class="n">token_prec</span> <span class="o">=</span> <span class="n">precedence</span> <span class="n">c</span> <span class="k">in</span>

      <span class="c">(* If this is a binop that binds at least as tightly as the current binop,</span>
<span class="c">       * consume it, otherwise we are done. *)</span>
      <span class="k">if</span> <span class="n">token_prec</span> <span class="o">&lt;</span> <span class="n">expr_prec</span> <span class="k">then</span> <span class="n">lhs</span> <span class="k">else</span> <span class="k">begin</span>
        <span class="c">(* Eat the binop. *)</span>
        <span class="nn">Stream</span><span class="p">.</span><span class="n">junk</span> <span class="n">stream</span><span class="o">;</span>

        <span class="c">(* Parse the primary expression after the binary operator. *)</span>
        <span class="k">let</span> <span class="n">rhs</span> <span class="o">=</span> <span class="n">parse_primary</span> <span class="n">stream</span> <span class="k">in</span>

        <span class="c">(* Okay, we know this is a binop. *)</span>
        <span class="k">let</span> <span class="n">rhs</span> <span class="o">=</span>
          <span class="k">match</span> <span class="nn">Stream</span><span class="p">.</span><span class="n">peek</span> <span class="n">stream</span> <span class="k">with</span>
          <span class="o">|</span> <span class="nc">Some</span> <span class="o">(</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Kwd</span> <span class="n">c2</span><span class="o">)</span> <span class="o">-&gt;</span>
              <span class="c">(* If BinOp binds less tightly with rhs than the operator after</span>
<span class="c">               * rhs, let the pending operator take rhs as its lhs. *)</span>
              <span class="k">let</span> <span class="n">next_prec</span> <span class="o">=</span> <span class="n">precedence</span> <span class="n">c2</span> <span class="k">in</span>
              <span class="k">if</span> <span class="n">token_prec</span> <span class="o">&lt;</span> <span class="n">next_prec</span>
              <span class="k">then</span> <span class="n">parse_bin_rhs</span> <span class="o">(</span><span class="n">token_prec</span> <span class="o">+</span> <span class="mi">1</span><span class="o">)</span> <span class="n">rhs</span> <span class="n">stream</span>
              <span class="k">else</span> <span class="n">rhs</span>
          <span class="o">|</span> <span class="o">_</span> <span class="o">-&gt;</span> <span class="n">rhs</span>
        <span class="k">in</span>

        <span class="c">(* Merge lhs/rhs. *)</span>
        <span class="k">let</span> <span class="n">lhs</span> <span class="o">=</span> <span class="nn">Ast</span><span class="p">.</span><span class="nc">Binary</span> <span class="o">(</span><span class="n">c</span><span class="o">,</span> <span class="n">lhs</span><span class="o">,</span> <span class="n">rhs</span><span class="o">)</span> <span class="k">in</span>
        <span class="n">parse_bin_rhs</span> <span class="n">expr_prec</span> <span class="n">lhs</span> <span class="n">stream</span>
      <span class="k">end</span>
  <span class="o">|</span> <span class="o">_</span> <span class="o">-&gt;</span> <span class="n">lhs</span>

<span class="c">(* expression</span>
<span class="c"> *   ::= primary binoprhs *)</span>
<span class="ow">and</span> <span class="n">parse_expr</span> <span class="o">=</span> <span class="n">parser</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="n">lhs</span><span class="o">=</span><span class="n">parse_primary</span><span class="o">;</span> <span class="n">stream</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="n">parse_bin_rhs</span> <span class="mi">0</span> <span class="n">lhs</span> <span class="n">stream</span>

<span class="c">(* prototype</span>
<span class="c"> *   ::= id &#39;(&#39; id* &#39;)&#39; *)</span>
<span class="k">let</span> <span class="n">parse_prototype</span> <span class="o">=</span>
  <span class="k">let</span> <span class="k">rec</span> <span class="n">parse_args</span> <span class="n">accumulator</span> <span class="o">=</span> <span class="n">parser</span>
    <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Ident</span> <span class="n">id</span><span class="o">;</span> <span class="n">e</span><span class="o">=</span><span class="n">parse_args</span> <span class="o">(</span><span class="n">id</span><span class="o">::</span><span class="n">accumulator</span><span class="o">)</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="n">e</span>
    <span class="o">|</span> <span class="o">[&lt;</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="n">accumulator</span>
  <span class="k">in</span>

  <span class="n">parser</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Ident</span> <span class="n">id</span><span class="o">;</span>
       <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Kwd</span> <span class="sc">&#39;(&#39;</span> <span class="o">??</span> <span class="s2">&quot;expected &#39;(&#39; in prototype&quot;</span><span class="o">;</span>
       <span class="n">args</span><span class="o">=</span><span class="n">parse_args</span> <span class="bp">[]</span><span class="o">;</span>
       <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Kwd</span> <span class="sc">&#39;)&#39;</span> <span class="o">??</span> <span class="s2">&quot;expected &#39;)&#39; in prototype&quot;</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span>
      <span class="c">(* success. *)</span>
      <span class="nn">Ast</span><span class="p">.</span><span class="nc">Prototype</span> <span class="o">(</span><span class="n">id</span><span class="o">,</span> <span class="nn">Array</span><span class="p">.</span><span class="n">of_list</span> <span class="o">(</span><span class="nn">List</span><span class="p">.</span><span class="n">rev</span> <span class="n">args</span><span class="o">))</span>

  <span class="o">|</span> <span class="o">[&lt;</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span>
      <span class="k">raise</span> <span class="o">(</span><span class="nn">Stream</span><span class="p">.</span><span class="nc">Error</span> <span class="s2">&quot;expected function name in prototype&quot;</span><span class="o">)</span>

<span class="c">(* definition ::= &#39;def&#39; prototype expression *)</span>
<span class="k">let</span> <span class="n">parse_definition</span> <span class="o">=</span> <span class="n">parser</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Def</span><span class="o">;</span> <span class="n">p</span><span class="o">=</span><span class="n">parse_prototype</span><span class="o">;</span> <span class="n">e</span><span class="o">=</span><span class="n">parse_expr</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span>
      <span class="nn">Ast</span><span class="p">.</span><span class="nc">Function</span> <span class="o">(</span><span class="n">p</span><span class="o">,</span> <span class="n">e</span><span class="o">)</span>

<span class="c">(* toplevelexpr ::= expression *)</span>
<span class="k">let</span> <span class="n">parse_toplevel</span> <span class="o">=</span> <span class="n">parser</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="n">e</span><span class="o">=</span><span class="n">parse_expr</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span>
      <span class="c">(* Make an anonymous proto. *)</span>
      <span class="nn">Ast</span><span class="p">.</span><span class="nc">Function</span> <span class="o">(</span><span class="nn">Ast</span><span class="p">.</span><span class="nc">Prototype</span> <span class="o">(</span><span class="s2">&quot;&quot;</span><span class="o">,</span> <span class="o">[||]),</span> <span class="n">e</span><span class="o">)</span>

<span class="c">(*  external ::= &#39;extern&#39; prototype *)</span>
<span class="k">let</span> <span class="n">parse_extern</span> <span class="o">=</span> <span class="n">parser</span>
  <span class="o">|</span> <span class="o">[&lt;</span> <span class="k">&#39;</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Extern</span><span class="o">;</span> <span class="n">e</span><span class="o">=</span><span class="n">parse_prototype</span> <span class="o">&gt;]</span> <span class="o">-&gt;</span> <span class="n">e</span>
</pre></div>
</div>
</dd>
<dt>codegen.ml:</dt>
<dd><div class="first last highlight-ocaml"><div class="highlight"><pre><span class="c">(*===----------------------------------------------------------------------===</span>
<span class="c"> * Code Generation</span>
<span class="c"> *===----------------------------------------------------------------------===*)</span>

<span class="k">open</span> <span class="nc">Llvm</span>

<span class="k">exception</span> <span class="nc">Error</span> <span class="k">of</span> <span class="kt">string</span>

<span class="k">let</span> <span class="n">context</span> <span class="o">=</span> <span class="n">global_context</span> <span class="bp">()</span>
<span class="k">let</span> <span class="n">the_module</span> <span class="o">=</span> <span class="n">create_module</span> <span class="n">context</span> <span class="s2">&quot;my cool jit&quot;</span>
<span class="k">let</span> <span class="n">builder</span> <span class="o">=</span> <span class="n">builder</span> <span class="n">context</span>
<span class="k">let</span> <span class="n">named_values</span><span class="o">:(</span><span class="kt">string</span><span class="o">,</span> <span class="n">llvalue</span><span class="o">)</span> <span class="nn">Hashtbl</span><span class="p">.</span><span class="n">t</span> <span class="o">=</span> <span class="nn">Hashtbl</span><span class="p">.</span><span class="n">create</span> <span class="mi">10</span>
<span class="k">let</span> <span class="n">double_type</span> <span class="o">=</span> <span class="n">double_type</span> <span class="n">context</span>

<span class="k">let</span> <span class="k">rec</span> <span class="n">codegen_expr</span> <span class="o">=</span> <span class="k">function</span>
  <span class="o">|</span> <span class="nn">Ast</span><span class="p">.</span><span class="nc">Number</span> <span class="n">n</span> <span class="o">-&gt;</span> <span class="n">const_float</span> <span class="n">double_type</span> <span class="n">n</span>
  <span class="o">|</span> <span class="nn">Ast</span><span class="p">.</span><span class="nc">Variable</span> <span class="n">name</span> <span class="o">-&gt;</span>
      <span class="o">(</span><span class="k">try</span> <span class="nn">Hashtbl</span><span class="p">.</span><span class="n">find</span> <span class="n">named_values</span> <span class="n">name</span> <span class="k">with</span>
        <span class="o">|</span> <span class="nc">Not_found</span> <span class="o">-&gt;</span> <span class="k">raise</span> <span class="o">(</span><span class="nc">Error</span> <span class="s2">&quot;unknown variable name&quot;</span><span class="o">))</span>
  <span class="o">|</span> <span class="nn">Ast</span><span class="p">.</span><span class="nc">Binary</span> <span class="o">(</span><span class="n">op</span><span class="o">,</span> <span class="n">lhs</span><span class="o">,</span> <span class="n">rhs</span><span class="o">)</span> <span class="o">-&gt;</span>
      <span class="k">let</span> <span class="n">lhs_val</span> <span class="o">=</span> <span class="n">codegen_expr</span> <span class="n">lhs</span> <span class="k">in</span>
      <span class="k">let</span> <span class="n">rhs_val</span> <span class="o">=</span> <span class="n">codegen_expr</span> <span class="n">rhs</span> <span class="k">in</span>
      <span class="k">begin</span>
        <span class="k">match</span> <span class="n">op</span> <span class="k">with</span>
        <span class="o">|</span> <span class="sc">&#39;+&#39;</span> <span class="o">-&gt;</span> <span class="n">build_add</span> <span class="n">lhs_val</span> <span class="n">rhs_val</span> <span class="s2">&quot;addtmp&quot;</span> <span class="n">builder</span>
        <span class="o">|</span> <span class="sc">&#39;-&#39;</span> <span class="o">-&gt;</span> <span class="n">build_sub</span> <span class="n">lhs_val</span> <span class="n">rhs_val</span> <span class="s2">&quot;subtmp&quot;</span> <span class="n">builder</span>
        <span class="o">|</span> <span class="sc">&#39;*&#39;</span> <span class="o">-&gt;</span> <span class="n">build_mul</span> <span class="n">lhs_val</span> <span class="n">rhs_val</span> <span class="s2">&quot;multmp&quot;</span> <span class="n">builder</span>
        <span class="o">|</span> <span class="sc">&#39;&lt;&#39;</span> <span class="o">-&gt;</span>
            <span class="c">(* Convert bool 0/1 to double 0.0 or 1.0 *)</span>
            <span class="k">let</span> <span class="n">i</span> <span class="o">=</span> <span class="n">build_fcmp</span> <span class="nn">Fcmp</span><span class="p">.</span><span class="nc">Ult</span> <span class="n">lhs_val</span> <span class="n">rhs_val</span> <span class="s2">&quot;cmptmp&quot;</span> <span class="n">builder</span> <span class="k">in</span>
            <span class="n">build_uitofp</span> <span class="n">i</span> <span class="n">double_type</span> <span class="s2">&quot;booltmp&quot;</span> <span class="n">builder</span>
        <span class="o">|</span> <span class="o">_</span> <span class="o">-&gt;</span> <span class="k">raise</span> <span class="o">(</span><span class="nc">Error</span> <span class="s2">&quot;invalid binary operator&quot;</span><span class="o">)</span>
      <span class="k">end</span>
  <span class="o">|</span> <span class="nn">Ast</span><span class="p">.</span><span class="nc">Call</span> <span class="o">(</span><span class="n">callee</span><span class="o">,</span> <span class="n">args</span><span class="o">)</span> <span class="o">-&gt;</span>
      <span class="c">(* Look up the name in the module table. *)</span>
      <span class="k">let</span> <span class="n">callee</span> <span class="o">=</span>
        <span class="k">match</span> <span class="n">lookup_function</span> <span class="n">callee</span> <span class="n">the_module</span> <span class="k">with</span>
        <span class="o">|</span> <span class="nc">Some</span> <span class="n">callee</span> <span class="o">-&gt;</span> <span class="n">callee</span>
        <span class="o">|</span> <span class="nc">None</span> <span class="o">-&gt;</span> <span class="k">raise</span> <span class="o">(</span><span class="nc">Error</span> <span class="s2">&quot;unknown function referenced&quot;</span><span class="o">)</span>
      <span class="k">in</span>
      <span class="k">let</span> <span class="n">params</span> <span class="o">=</span> <span class="n">params</span> <span class="n">callee</span> <span class="k">in</span>

      <span class="c">(* If argument mismatch error. *)</span>
      <span class="k">if</span> <span class="nn">Array</span><span class="p">.</span><span class="n">length</span> <span class="n">params</span> <span class="o">==</span> <span class="nn">Array</span><span class="p">.</span><span class="n">length</span> <span class="n">args</span> <span class="k">then</span> <span class="bp">()</span> <span class="k">else</span>
        <span class="k">raise</span> <span class="o">(</span><span class="nc">Error</span> <span class="s2">&quot;incorrect # arguments passed&quot;</span><span class="o">);</span>
      <span class="k">let</span> <span class="n">args</span> <span class="o">=</span> <span class="nn">Array</span><span class="p">.</span><span class="n">map</span> <span class="n">codegen_expr</span> <span class="n">args</span> <span class="k">in</span>
      <span class="n">build_call</span> <span class="n">callee</span> <span class="n">args</span> <span class="s2">&quot;calltmp&quot;</span> <span class="n">builder</span>

<span class="k">let</span> <span class="n">codegen_proto</span> <span class="o">=</span> <span class="k">function</span>
  <span class="o">|</span> <span class="nn">Ast</span><span class="p">.</span><span class="nc">Prototype</span> <span class="o">(</span><span class="n">name</span><span class="o">,</span> <span class="n">args</span><span class="o">)</span> <span class="o">-&gt;</span>
      <span class="c">(* Make the function type: double(double,double) etc. *)</span>
      <span class="k">let</span> <span class="n">doubles</span> <span class="o">=</span> <span class="nn">Array</span><span class="p">.</span><span class="n">make</span> <span class="o">(</span><span class="nn">Array</span><span class="p">.</span><span class="n">length</span> <span class="n">args</span><span class="o">)</span> <span class="n">double_type</span> <span class="k">in</span>
      <span class="k">let</span> <span class="n">ft</span> <span class="o">=</span> <span class="n">function_type</span> <span class="n">double_type</span> <span class="n">doubles</span> <span class="k">in</span>
      <span class="k">let</span> <span class="n">f</span> <span class="o">=</span>
        <span class="k">match</span> <span class="n">lookup_function</span> <span class="n">name</span> <span class="n">the_module</span> <span class="k">with</span>
        <span class="o">|</span> <span class="nc">None</span> <span class="o">-&gt;</span> <span class="n">declare_function</span> <span class="n">name</span> <span class="n">ft</span> <span class="n">the_module</span>

        <span class="c">(* If &#39;f&#39; conflicted, there was already something named &#39;name&#39;. If it</span>
<span class="c">         * has a body, don&#39;t allow redefinition or reextern. *)</span>
        <span class="o">|</span> <span class="nc">Some</span> <span class="n">f</span> <span class="o">-&gt;</span>
            <span class="c">(* If &#39;f&#39; already has a body, reject this. *)</span>
            <span class="k">if</span> <span class="n">block_begin</span> <span class="n">f</span> <span class="o">&lt;&gt;</span> <span class="nc">At_end</span> <span class="n">f</span> <span class="k">then</span>
              <span class="k">raise</span> <span class="o">(</span><span class="nc">Error</span> <span class="s2">&quot;redefinition of function&quot;</span><span class="o">);</span>

            <span class="c">(* If &#39;f&#39; took a different number of arguments, reject. *)</span>
            <span class="k">if</span> <span class="n">element_type</span> <span class="o">(</span><span class="n">type_of</span> <span class="n">f</span><span class="o">)</span> <span class="o">&lt;&gt;</span> <span class="n">ft</span> <span class="k">then</span>
              <span class="k">raise</span> <span class="o">(</span><span class="nc">Error</span> <span class="s2">&quot;redefinition of function with different # args&quot;</span><span class="o">);</span>
            <span class="n">f</span>
      <span class="k">in</span>

      <span class="c">(* Set names for all arguments. *)</span>
      <span class="nn">Array</span><span class="p">.</span><span class="n">iteri</span> <span class="o">(</span><span class="k">fun</span> <span class="n">i</span> <span class="n">a</span> <span class="o">-&gt;</span>
        <span class="k">let</span> <span class="n">n</span> <span class="o">=</span> <span class="n">args</span><span class="o">.(</span><span class="n">i</span><span class="o">)</span> <span class="k">in</span>
        <span class="n">set_value_name</span> <span class="n">n</span> <span class="n">a</span><span class="o">;</span>
        <span class="nn">Hashtbl</span><span class="p">.</span><span class="n">add</span> <span class="n">named_values</span> <span class="n">n</span> <span class="n">a</span><span class="o">;</span>
      <span class="o">)</span> <span class="o">(</span><span class="n">params</span> <span class="n">f</span><span class="o">);</span>
      <span class="n">f</span>

<span class="k">let</span> <span class="n">codegen_func</span> <span class="n">the_fpm</span> <span class="o">=</span> <span class="k">function</span>
  <span class="o">|</span> <span class="nn">Ast</span><span class="p">.</span><span class="nc">Function</span> <span class="o">(</span><span class="n">proto</span><span class="o">,</span> <span class="n">body</span><span class="o">)</span> <span class="o">-&gt;</span>
      <span class="nn">Hashtbl</span><span class="p">.</span><span class="n">clear</span> <span class="n">named_values</span><span class="o">;</span>
      <span class="k">let</span> <span class="n">the_function</span> <span class="o">=</span> <span class="n">codegen_proto</span> <span class="n">proto</span> <span class="k">in</span>

      <span class="c">(* Create a new basic block to start insertion into. *)</span>
      <span class="k">let</span> <span class="n">bb</span> <span class="o">=</span> <span class="n">append_block</span> <span class="n">context</span> <span class="s2">&quot;entry&quot;</span> <span class="n">the_function</span> <span class="k">in</span>
      <span class="n">position_at_end</span> <span class="n">bb</span> <span class="n">builder</span><span class="o">;</span>

      <span class="k">try</span>
        <span class="k">let</span> <span class="n">ret_val</span> <span class="o">=</span> <span class="n">codegen_expr</span> <span class="n">body</span> <span class="k">in</span>

        <span class="c">(* Finish off the function. *)</span>
        <span class="k">let</span> <span class="o">_</span> <span class="o">=</span> <span class="n">build_ret</span> <span class="n">ret_val</span> <span class="n">builder</span> <span class="k">in</span>

        <span class="c">(* Validate the generated code, checking for consistency. *)</span>
        <span class="nn">Llvm_analysis</span><span class="p">.</span><span class="n">assert_valid_function</span> <span class="n">the_function</span><span class="o">;</span>

        <span class="c">(* Optimize the function. *)</span>
        <span class="k">let</span> <span class="o">_</span> <span class="o">=</span> <span class="nn">PassManager</span><span class="p">.</span><span class="n">run_function</span> <span class="n">the_function</span> <span class="n">the_fpm</span> <span class="k">in</span>

        <span class="n">the_function</span>
      <span class="k">with</span> <span class="n">e</span> <span class="o">-&gt;</span>
        <span class="n">delete_function</span> <span class="n">the_function</span><span class="o">;</span>
        <span class="k">raise</span> <span class="n">e</span>
</pre></div>
</div>
</dd>
<dt>toplevel.ml:</dt>
<dd><div class="first last highlight-ocaml"><div class="highlight"><pre><span class="c">(*===----------------------------------------------------------------------===</span>
<span class="c"> * Top-Level parsing and JIT Driver</span>
<span class="c"> *===----------------------------------------------------------------------===*)</span>

<span class="k">open</span> <span class="nc">Llvm</span>
<span class="k">open</span> <span class="nc">Llvm_executionengine</span>

<span class="c">(* top ::= definition | external | expression | &#39;;&#39; *)</span>
<span class="k">let</span> <span class="k">rec</span> <span class="n">main_loop</span> <span class="n">the_fpm</span> <span class="n">the_execution_engine</span> <span class="n">stream</span> <span class="o">=</span>
  <span class="k">match</span> <span class="nn">Stream</span><span class="p">.</span><span class="n">peek</span> <span class="n">stream</span> <span class="k">with</span>
  <span class="o">|</span> <span class="nc">None</span> <span class="o">-&gt;</span> <span class="bp">()</span>

  <span class="c">(* ignore top-level semicolons. *)</span>
  <span class="o">|</span> <span class="nc">Some</span> <span class="o">(</span><span class="nn">Token</span><span class="p">.</span><span class="nc">Kwd</span> <span class="sc">&#39;;&#39;</span><span class="o">)</span> <span class="o">-&gt;</span>
      <span class="nn">Stream</span><span class="p">.</span><span class="n">junk</span> <span class="n">stream</span><span class="o">;</span>
      <span class="n">main_loop</span> <span class="n">the_fpm</span> <span class="n">the_execution_engine</span> <span class="n">stream</span>

  <span class="o">|</span> <span class="nc">Some</span> <span class="n">token</span> <span class="o">-&gt;</span>
      <span class="k">begin</span>
        <span class="k">try</span> <span class="k">match</span> <span class="n">token</span> <span class="k">with</span>
        <span class="o">|</span> <span class="nn">Token</span><span class="p">.</span><span class="nc">Def</span> <span class="o">-&gt;</span>
            <span class="k">let</span> <span class="n">e</span> <span class="o">=</span> <span class="nn">Parser</span><span class="p">.</span><span class="n">parse_definition</span> <span class="n">stream</span> <span class="k">in</span>
            <span class="n">print_endline</span> <span class="s2">&quot;parsed a function definition.&quot;</span><span class="o">;</span>
            <span class="n">dump_value</span> <span class="o">(</span><span class="nn">Codegen</span><span class="p">.</span><span class="n">codegen_func</span> <span class="n">the_fpm</span> <span class="n">e</span><span class="o">);</span>
        <span class="o">|</span> <span class="nn">Token</span><span class="p">.</span><span class="nc">Extern</span> <span class="o">-&gt;</span>
            <span class="k">let</span> <span class="n">e</span> <span class="o">=</span> <span class="nn">Parser</span><span class="p">.</span><span class="n">parse_extern</span> <span class="n">stream</span> <span class="k">in</span>
            <span class="n">print_endline</span> <span class="s2">&quot;parsed an extern.&quot;</span><span class="o">;</span>
            <span class="n">dump_value</span> <span class="o">(</span><span class="nn">Codegen</span><span class="p">.</span><span class="n">codegen_proto</span> <span class="n">e</span><span class="o">);</span>
        <span class="o">|</span> <span class="o">_</span> <span class="o">-&gt;</span>
            <span class="c">(* Evaluate a top-level expression into an anonymous function. *)</span>
            <span class="k">let</span> <span class="n">e</span> <span class="o">=</span> <span class="nn">Parser</span><span class="p">.</span><span class="n">parse_toplevel</span> <span class="n">stream</span> <span class="k">in</span>
            <span class="n">print_endline</span> <span class="s2">&quot;parsed a top-level expr&quot;</span><span class="o">;</span>
            <span class="k">let</span> <span class="n">the_function</span> <span class="o">=</span> <span class="nn">Codegen</span><span class="p">.</span><span class="n">codegen_func</span> <span class="n">the_fpm</span> <span class="n">e</span> <span class="k">in</span>
            <span class="n">dump_value</span> <span class="n">the_function</span><span class="o">;</span>

            <span class="c">(* JIT the function, returning a function pointer. *)</span>
            <span class="k">let</span> <span class="n">result</span> <span class="o">=</span> <span class="nn">ExecutionEngine</span><span class="p">.</span><span class="n">run_function</span> <span class="n">the_function</span> <span class="o">[||]</span>
              <span class="n">the_execution_engine</span> <span class="k">in</span>

            <span class="n">print_string</span> <span class="s2">&quot;Evaluated to &quot;</span><span class="o">;</span>
            <span class="n">print_float</span> <span class="o">(</span><span class="nn">GenericValue</span><span class="p">.</span><span class="n">as_float</span> <span class="nn">Codegen</span><span class="p">.</span><span class="n">double_type</span> <span class="n">result</span><span class="o">);</span>
            <span class="n">print_newline</span> <span class="bp">()</span><span class="o">;</span>
        <span class="k">with</span> <span class="nn">Stream</span><span class="p">.</span><span class="nc">Error</span> <span class="n">s</span> <span class="o">|</span> <span class="nn">Codegen</span><span class="p">.</span><span class="nc">Error</span> <span class="n">s</span> <span class="o">-&gt;</span>
          <span class="c">(* Skip token for error recovery. *)</span>
          <span class="nn">Stream</span><span class="p">.</span><span class="n">junk</span> <span class="n">stream</span><span class="o">;</span>
          <span class="n">print_endline</span> <span class="n">s</span><span class="o">;</span>
      <span class="k">end</span><span class="o">;</span>
      <span class="n">print_string</span> <span class="s2">&quot;ready&gt; &quot;</span><span class="o">;</span> <span class="n">flush</span> <span class="n">stdout</span><span class="o">;</span>
      <span class="n">main_loop</span> <span class="n">the_fpm</span> <span class="n">the_execution_engine</span> <span class="n">stream</span>
</pre></div>
</div>
</dd>
<dt>toy.ml:</dt>
<dd><div class="first last highlight-ocaml"><div class="highlight"><pre><span class="c">(*===----------------------------------------------------------------------===</span>
<span class="c"> * Main driver code.</span>
<span class="c"> *===----------------------------------------------------------------------===*)</span>

<span class="k">open</span> <span class="nc">Llvm</span>
<span class="k">open</span> <span class="nc">Llvm_executionengine</span>
<span class="k">open</span> <span class="nc">Llvm_target</span>
<span class="k">open</span> <span class="nc">Llvm_scalar_opts</span>

<span class="k">let</span> <span class="n">main</span> <span class="bp">()</span> <span class="o">=</span>
  <span class="n">ignore</span> <span class="o">(</span><span class="n">initialize_native_target</span> <span class="bp">()</span><span class="o">);</span>

  <span class="c">(* Install standard binary operators.</span>
<span class="c">   * 1 is the lowest precedence. *)</span>
  <span class="nn">Hashtbl</span><span class="p">.</span><span class="n">add</span> <span class="nn">Parser</span><span class="p">.</span><span class="n">binop_precedence</span> <span class="sc">&#39;&lt;&#39;</span> <span class="mi">10</span><span class="o">;</span>
  <span class="nn">Hashtbl</span><span class="p">.</span><span class="n">add</span> <span class="nn">Parser</span><span class="p">.</span><span class="n">binop_precedence</span> <span class="sc">&#39;+&#39;</span> <span class="mi">20</span><span class="o">;</span>
  <span class="nn">Hashtbl</span><span class="p">.</span><span class="n">add</span> <span class="nn">Parser</span><span class="p">.</span><span class="n">binop_precedence</span> <span class="sc">&#39;-&#39;</span> <span class="mi">20</span><span class="o">;</span>
  <span class="nn">Hashtbl</span><span class="p">.</span><span class="n">add</span> <span class="nn">Parser</span><span class="p">.</span><span class="n">binop_precedence</span> <span class="sc">&#39;*&#39;</span> <span class="mi">40</span><span class="o">;</span>    <span class="c">(* highest. *)</span>

  <span class="c">(* Prime the first token. *)</span>
  <span class="n">print_string</span> <span class="s2">&quot;ready&gt; &quot;</span><span class="o">;</span> <span class="n">flush</span> <span class="n">stdout</span><span class="o">;</span>
  <span class="k">let</span> <span class="n">stream</span> <span class="o">=</span> <span class="nn">Lexer</span><span class="p">.</span><span class="n">lex</span> <span class="o">(</span><span class="nn">Stream</span><span class="p">.</span><span class="n">of_channel</span> <span class="n">stdin</span><span class="o">)</span> <span class="k">in</span>

  <span class="c">(* Create the JIT. *)</span>
  <span class="k">let</span> <span class="n">the_execution_engine</span> <span class="o">=</span> <span class="nn">ExecutionEngine</span><span class="p">.</span><span class="n">create</span> <span class="nn">Codegen</span><span class="p">.</span><span class="n">the_module</span> <span class="k">in</span>
  <span class="k">let</span> <span class="n">the_fpm</span> <span class="o">=</span> <span class="nn">PassManager</span><span class="p">.</span><span class="n">create_function</span> <span class="nn">Codegen</span><span class="p">.</span><span class="n">the_module</span> <span class="k">in</span>

  <span class="c">(* Set up the optimizer pipeline.  Start with registering info about how the</span>
<span class="c">   * target lays out data structures. *)</span>
  <span class="nn">DataLayout</span><span class="p">.</span><span class="n">add</span> <span class="o">(</span><span class="nn">ExecutionEngine</span><span class="p">.</span><span class="n">target_data</span> <span class="n">the_execution_engine</span><span class="o">)</span> <span class="n">the_fpm</span><span class="o">;</span>

  <span class="c">(* Do simple &quot;peephole&quot; optimizations and bit-twiddling optzn. *)</span>
  <span class="n">add_instruction_combination</span> <span class="n">the_fpm</span><span class="o">;</span>

  <span class="c">(* reassociate expressions. *)</span>
  <span class="n">add_reassociation</span> <span class="n">the_fpm</span><span class="o">;</span>

  <span class="c">(* Eliminate Common SubExpressions. *)</span>
  <span class="n">add_gvn</span> <span class="n">the_fpm</span><span class="o">;</span>

  <span class="c">(* Simplify the control flow graph (deleting unreachable blocks, etc). *)</span>
  <span class="n">add_cfg_simplification</span> <span class="n">the_fpm</span><span class="o">;</span>

  <span class="n">ignore</span> <span class="o">(</span><span class="nn">PassManager</span><span class="p">.</span><span class="n">initialize</span> <span class="n">the_fpm</span><span class="o">);</span>

  <span class="c">(* Run the main &quot;interpreter loop&quot; now. *)</span>
  <span class="nn">Toplevel</span><span class="p">.</span><span class="n">main_loop</span> <span class="n">the_fpm</span> <span class="n">the_execution_engine</span> <span class="n">stream</span><span class="o">;</span>

  <span class="c">(* Print out all the generated code. *)</span>
  <span class="n">dump_module</span> <span class="nn">Codegen</span><span class="p">.</span><span class="n">the_module</span>
<span class="o">;;</span>

<span class="n">main</span> <span class="bp">()</span>
</pre></div>
</div>
</dd>
<dt>bindings.c</dt>
<dd><div class="first last highlight-c"><div class="highlight"><pre><span class="cp">#include &lt;stdio.h&gt;</span>

<span class="cm">/* putchard - putchar that takes a double and returns 0. */</span>
<span class="k">extern</span> <span class="kt">double</span> <span class="nf">putchard</span><span class="p">(</span><span class="kt">double</span> <span class="n">X</span><span class="p">)</span> <span class="p">{</span>
  <span class="n">putchar</span><span class="p">((</span><span class="kt">char</span><span class="p">)</span><span class="n">X</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
</dd>
</dl>
<p><a class="reference external" href="OCamlLangImpl5.html">Next: Extending the language: control flow</a></p>
</div>
</div>


          </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="OCamlLangImpl5.html" title="5. Kaleidoscope: Extending the Language: Control Flow"
             >next</a> |</li>
        <li class="right" >
          <a href="OCamlLangImpl3.html" title="3. Kaleidoscope: Code generation to LLVM IR"
             >previous</a> |</li>
  <li><a href="http://llvm.org/">LLVM Home</a>&nbsp;|&nbsp;</li>
  <li><a href="../index.html">Documentation</a>&raquo;</li>

          <li class="nav-item nav-item-1"><a href="index.html" >LLVM Tutorial: Table of Contents</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer" role="contentinfo">
        &copy; Copyright 2003-2015, LLVM Project.
      Last updated on 2015-09-08.
      Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.3.1.
    </div>
  </body>
</html>